package ch.utilities;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ch.exception.BadEmailAddressException;


/** Classe per la gestione del FriendlyName negli indirizzi email.
*
* @author Neil Otupacca - May 21 2011
*
*/
public class FriendlyNameAddress {

	private boolean flFriendlyName;
	private String friendlyName;
	private String emailAddress;

	public FriendlyNameAddress(String address) {
		String re = "^(?:(\"?)([^\"<\\r\\n]+?)\\1\\s*" +
					"<([^\\x00-,\\./:-@\\[-`\\{-\\xff]+" +
					"(?:\\.[^\\x00-,\\./:-@\\[-`\\{-\\xff]+)*@" +
					"[^\\x00-,\\./:-@\\[-`\\{-\\xff]+" +
					"(?:\\.[^\\x00-,\\./:-@\\[-`\\{-\\xff]+)+)>|" +
					"([^\\x00-,\\./:-@\\[-`\\{-\\xff]+" +
					"(?:\\.[^\\x00-,\\./:-@\\[-`\\{-\\xff]+)*@" +
					"[^\\x00-,\\./:-@\\[-`\\{-\\xff]+" +
					"(?:\\.[^\\x00-,\\./:-@\\[-`\\{-\\xff]+)+))$";

		Pattern pat = Pattern.compile(re);
		Matcher matcher = pat.matcher(address);

		// Errore di formato Email
		if (!matcher.find()) throw new BadEmailAddressException();

		if (matcher.group(2) != null) {
			flFriendlyName = true;
			friendlyName = matcher.group(2);
			emailAddress = matcher.group(3);
		}
		else {
			flFriendlyName = false;
			friendlyName = "";
			emailAddress = matcher.group(4);
		}
	}

	/** Ritorna <b>true</b> se l'indirizzo email ha un <i>friendlyName</i>.
	 *
	 * @return <b>true</b> o <b>false</b>.
	 */
	public boolean haveFriendlaName() {
		return(flFriendlyName);
	}

	/** Ritorna il <i>friendlyName</i> se esiste.
	 *
	 * @return stringa del <i>friendlyName</i>.
	 */
	public String getFriendlyName() {
		return(friendlyName);
	}

	/** Ritorna l'indirizzo email.
	 *
	 * @return string dell'indirizzo email.
	 */
	public String getAddressEmail() {
		return(emailAddress);
	}
}
